//
//  ModelChoiceButton.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/27.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "ModelChoiceButton.h"
#import "UIImageView+WebCache.h"

@implementation ModelChoiceButton{
    NSURLConnection *connection_;
    NSMutableData *responseData_;
    UIImage *img;
}

-(void)dealloc{
    img = nil;
    connection_ = nil;
    responseData_ = nil;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)buttonWithUrl:(NSString *)urlstr{
    // UIImage *backImg = []
    
   NSURL *url = [NSURL URLWithString:urlstr];
//
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
//    connection_ = [NSURLConnection connectionWithRequest:request delegate:self];
    
    [self sd_setBackgroundImageWithURL:url forState:UIControlStateNormal placeholderImage:PLACE_HODER_IMG];
    
}

#pragma mark - NSURLConnectionDataDelegate Delegate Method

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    NSLog(@"didFailWithError:%@", error);
    connection_ = nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    NSLog(@"didReceiveResponse");
    responseData_ = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSLog(@"didReceiveData");
    [responseData_ appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    NSLog(@"connectionDidFinishLoading");
    img = [UIImage imageWithData:responseData_];
    [self setBackgroundImage:img forState:UIControlStateNormal];
    connection_ = nil;
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    
    NSLog(@"[已缓存数据]willCacheResponse\ncache_response:%@\ncache_data:%@", cachedResponse.response, cachedResponse.data);
    return cachedResponse;
}



@end
